<template>
  <div class="address-card">
    <el-card>
      <!--地址展示-->
      <div v-show="!edit">
        <el-button type="text" class="edit-btn" @click.stop.prevent="showEdit">修改</el-button>
        <el-form label-width="6em">
          <el-form-item label="姓名:">
            <div>{{address.name}}</div>
          </el-form-item>
          <el-form-item label="电话:">
            <div>{{address.phone}}</div>
          </el-form-item>
          <el-form-item label="地区:">
            <div>{{addressAreaStr}}</div>
          </el-form-item>
          <el-form-item label="详细地址:">
            <div>{{address.text}}</div>
          </el-form-item>
        </el-form>
      </div>

      <!--地址编辑-->
      <div v-show="edit">
        <el-form :model="form" :rules="rules" ref="form" label-width="6em">
          <el-form-item label="姓名:" prop="name">
            <el-input v-model="form.name" placeholder="请输入姓名"></el-input>
          </el-form-item>
          <el-form-item label="电话:" prop="phone">
            <el-input v-model="form.phone" placeholder="请输入电话"></el-input>
          </el-form-item>
          <el-form-item label="地区:" prop="area">
            <el-cascader style="width: 100%"
               v-model="form.area"
               :options="areaList"
               :props="areaProps"
               @change="handleChange">
            </el-cascader>
          </el-form-item>
          <el-form-item label="详细地址:" prop="text">
            <el-input v-model="form.text" placeholder="请输入详细地址"></el-input>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="submitForm('form')">{{isNew?'添加':'保存'}}</el-button>
            <el-button @click="cancel('form')">取消</el-button>
          </el-form-item>

        </el-form>
      </div>

    </el-card>
  </div>
</template>

<script>
  import {insertContact,modifyContact} from '@/api/user';
  import {showMessage} from '@/utils/message';
  import {validatePhoneNum} from '@/utils/validate';

  export default {
    name:'addressCard',
    props:{
      isNew:
      {
        type:Boolean,
        default:false, //是否是新增地址，默认不是
      },
      address:{
        type:Object,
        default:()=> {
          return {};  //传入的地址数据
        }
      },
    },
    data() {
      const validatePhone = (rule, value, callback) =>
      {
        if (value.length <=0)
        {
          callback(new Error('请输入联系人手机号'));
        }
        else if(!validatePhoneNum(value))
        {
          callback(new Error('手机号格式不正确'))
        }
        else
        {
          callback()
        }
      };
      const validateArea = (rule, value, callback) =>{
        if(!this.form.provice && !this.form.city && !this.form.regoin)
        {
          callback(new Error('请选择地区'));
        }
        else
        {
          callback();
        }
      };
      return {
        edit:false, //是否显示编辑
        form:{ //编辑，新增表单
          name:this.address.name || '',
          phone:this.address.phone || '',
          provice:this.address.provice || '',
          city:this.address.city || '',
          regoin: this.address.regoin || '',
          text: this.address.text || '',
          area:[this.address.provice,this.address.city,this.address.regoin], //用于取回编辑
        },
        rules:{
          name: [
            {required:true,message:'请输入联系人姓名',trigger: 'blur' }
            ],
          phone:[
            {required:true,validator: validatePhone,trigger:'blur'},
          ],
          area:[
            {required:true,validator: validateArea,trigger:'change'},
          ],
          text:[
            {required:true,message:'请输入联系人详细地址',trigger:'blur'},
          ],
        },
        areaProps:{label:'name',value:'name',children:'children'}, //省市区属性
      };
    },
    computed:{
      addressAreaStr() //显示地址区域拼接后的字符串
      {
         let adds = [];
         adds.push(this.address.provice || '-',this.address.city || '-',this.address.regoin || '-');
         return adds.join(' / ');
      },
      areaList() //省市区列表
      {
        return this.$store.getters.area;
      },
    },
    methods: {
      handleChange(value) {
        this.form.provice = value[0];
        this.form.city = value[1];
        this.form.regoin = value[2];
      },
      submitForm(formName)
      {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            let data = {
              name:this.form.name,
              phone:this.form.phone,
              provice:this.form.provice,
              city:this.form.city,
              regoin:this.form.regoin,
              text:this.form.text,
            };

            if(this.isNew)
            {
              insertContact(data).then((resp)=>{
                this.edit = false;
                showMessage({title:'添加成功',type:'success'});
                this.$emit('success');

                //更新缓存的地址列表
                this.$store.dispatch('getContactList',{reload:true, data:{pageNum:1,pageSize:999}});

              }).catch((err)=>{
                //console.log(err);
              })
            }
            else
            {
              data.id=this.address.id;
              data.version = this.address.version;
              modifyContact(data).then((resp)=>{
                this.edit = false;
                showMessage({title:'修改成功',type:'success'});
                this.$emit('success');

                //更新缓存的地址列表
                this.$store.dispatch('getContactList',{reload:true, data:{pageNum:1,pageSize:999}});

              }).catch((err)=>{

              });

            }

          } else {
            return false;
          }
        });
      },
      showEdit()
      {
         this.edit = true;
         let areaLoaded = this.$store.getters.areaLoaded;
         if(!areaLoaded)
         {
           this.$store.dispatch('GenerateArea');
         }
      },
      cancel(formName)
      {
        this.$confirm('确定取消保存?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'info'
        }).then(() => {
          if(this.isNew)
          {
            this.edit = false;
            this.$emit('cancel');
          }
          else
          {
             this.edit = false;
          }
        }).catch(() => {

        });
      }
    },
    mounted()
    {
       if(this.isNew)
       {
         this.showEdit()
       }
    },

  };
</script>

<style lang="scss" scoped>
  @import "../../../styles/mixin";
  .address-card
  {
     margin-bottom: 20px;

     .el-card
     {
       box-shadow: none;
       width: 600px;
       padding: 30px 60px 0 0;
       position: relative;

       .edit-btn
       {
         position: absolute;
         right: 20px;
         top: 10px;
         display: none;
       }

       &:hover
       {
         box-shadow: 0 2px 4px 0 rgba(0,0,0,.12), 0 0 6px 0 rgba(0,0,0,.04);

         .edit-btn
         {
           display: block;
         }

       }

     }

    @include clearfix;
  }
</style>